//! R-XShell - A Rust implementation of xshell-like functionality
//!
//! This is the main entry point for the R-XShell command-line tool.

use clap::{Arg, Command as ClapCommand};
use r_xshell::prelude::*;
use std::process;

#[tokio::main]
async fn main() {
    // Initialize logging
    env_logger::init();
    
    let matches = ClapCommand::new("r-xshell")
        .version("0.1.0")
        .author("R-XShell Team")
        .about("A Rust implementation of xshell-like functionality")
        .arg(
            Arg::new("command")
                .help("Command to execute")
                .required(false)
                .index(1)
        )
        .arg(
            Arg::new("args")
                .help("Arguments for the command")
                .num_args(0..)
                .index(2)
        )
        .arg(
            Arg::new("config")
                .short('c')
                .long("config")
                .value_name("FILE")
                .help("Configuration file path")
                .value_parser(clap::value_parser!(String))
        )
        .arg(
            Arg::new("timeout")
                .short('t')
                .long("timeout")
                .value_name("SECONDS")
                .help("Command timeout in seconds")
                .value_parser(clap::value_parser!(String))
        )
        .arg(
            Arg::new("verbose")
                .short('v')
                .long("verbose")
                .help("Enable verbose output")
                .action(clap::ArgAction::SetTrue)
        )
        .arg(
            Arg::new("demo")
                .long("demo")
                .help("Run demonstration of R-XShell capabilities")
                .action(clap::ArgAction::SetTrue)
        )
        .get_matches();
    
    // Handle demo mode
    if matches.get_flag("demo") {
        if let Err(e) = run_demo().await {
            eprintln!("Demo failed: {}", e);
            process::exit(1);
        }
        return;
    }
    
    // Create shell instance
    let shell = match create_shell(&matches) {
        Ok(shell) => shell,
        Err(e) => {
            eprintln!("Failed to create shell: {}", e);
            process::exit(1);
        }
    };
    
    // Execute command if provided
    if let Some(program) = matches.get_one::<String>("command") {
        let args: Vec<String> = matches.get_many::<String>("args")
            .unwrap_or_default()
            .map(|s| s.clone())
            .collect();
        
        let mut command = Command::new(program);
        if !args.is_empty() {
            command = command.args(args);
        }
        
        // Set timeout if provided
        if let Some(timeout_str) = matches.get_one::<String>("timeout") {
            if let Ok(timeout_secs) = timeout_str.parse::<u64>() {
                command = command.timeout(std::time::Duration::from_secs(timeout_secs));
            }
        }
        
        match shell.run(&command).await {
            Ok(result) => {
                if matches.get_flag("verbose") {
                    println!("Exit code: {:?}", result.exit_code);
                    println!("Duration: {:?}", result.duration);
                    println!("--- STDOUT ---");
                }
                print!("{}", result.stdout);
                
                if matches.get_flag("verbose") && !result.stderr.is_empty() {
                    println!("--- STDERR ---");
                    eprint!("{}", result.stderr);
                }
                
                if !result.is_success() {
                    process::exit(result.exit_code.unwrap_or(1));
                }
            }
            Err(e) => {
                eprintln!("Command execution failed: {}", e);
                process::exit(1);
            }
        }
    } else {
        // Interactive mode or help
        println!("R-XShell v0.1.0 - A Rust implementation of xshell-like functionality");
        println!();
        println!("Usage examples:");
        println!("  r-xshell ls -la");
        println!("  r-xshell --demo");
        println!("  r-xshell --config config.json echo \"Hello, World!\"");
        println!();
        println!("For more information, use --help");
    }
}

/// Create a shell instance based on command line arguments
fn create_shell(matches: &clap::ArgMatches) -> Result<Shell> {
    if let Some(config_path) = matches.get_one::<String>("config") {
        Shell::from_config_file(config_path)
    } else {
        Shell::from_env()
    }
}

/// Run a demonstration of R-XShell capabilities
async fn run_demo() -> Result<()> {
    println!("🚀 R-XShell Demo - Showcasing Architecture and Capabilities");
    println!("{}", "=".repeat(60));
    
    // Create shell with custom configuration
    let config = Config::new();
    let shell = Shell::with_config(config)?;
    
    println!("\n📁 Current working directory:");
    println!("   {}", shell.current_dir().display());
    
    // Demonstrate basic command execution
    println!("\n🔧 Basic Command Execution:");
    
    #[cfg(windows)]
    let test_commands = vec![
        ("echo", vec!["Hello from R-XShell!"]),
        ("dir", vec!["/b"]),
        ("echo", vec!["Current time:"]),
        ("time", vec!["/t"]),
    ];
    
    #[cfg(not(windows))]
    let test_commands = vec![
        ("echo", vec!["Hello from R-XShell!"]),
        ("ls", vec!["-la"]),
        ("echo", vec!["Current time:"]),
        ("date", vec![]),
    ];
    
    for (program, args) in test_commands {
        let command = Command::new(program).args(args);
        println!("   Executing: {}", command.command_line());
        
        match shell.run(&command).await {
            Ok(result) => {
                if result.is_success() {
                    println!("   ✅ Success ({}ms)", result.duration.as_millis());
                    if !result.stdout.trim().is_empty() {
                        println!("   📤 Output: {}", result.stdout.trim());
                    }
                } else {
                    println!("   ❌ Failed with exit code: {:?}", result.exit_code);
                }
            }
            Err(e) => {
                println!("   ❌ Error: {}", e);
            }
        }
        println!();
    }
    
    // Demonstrate concurrent execution
    println!("🔄 Concurrent Command Execution:");
    let concurrent_commands = vec![
        Command::new("echo").arg("Task 1"),
        Command::new("echo").arg("Task 2"),
        Command::new("echo").arg("Task 3"),
    ];
    
    let start_time = std::time::Instant::now();
    let results = shell.run_concurrent(concurrent_commands).await;
    let total_time = start_time.elapsed();
    
    println!("   Executed {} commands concurrently in {}ms", results.len(), total_time.as_millis());
    for (i, result) in results.iter().enumerate() {
        match result {
            Ok(exec_result) => {
                println!("   Task {}: ✅ {}", i + 1, exec_result.stdout.trim());
            }
            Err(e) => {
                println!("   Task {}: ❌ {}", i + 1, e);
            }
        }
    }
    
    println!("\n🏗️  Architecture Overview:");
    println!("   📦 Modular Design:");
    println!("      • Command: Type-safe command building");
    println!("      • Executor: Async/concurrent execution engine");
    println!("      • Config: Flexible configuration management");
    println!("      • Shell: High-level interface");
    println!("      • Utils: File system, path, and environment utilities");
    println!("   ");
    println!("   🔒 Security Features:");
    println!("      • Command validation");
    println!("      • Shell injection protection");
    println!("      • Configurable command restrictions");
    println!("   ");
    println!("   ⚡ Performance Features:");
    println!("      • Async/await support");
    println!("      • Concurrent execution");
    println!("      • Configurable timeouts");
    println!("      • Resource management");
    
    println!("\n✨ Demo completed successfully!");
    println!("   The architecture is designed for:");
    println!("   • Extensibility: Easy to add new features");
    println!("   • Reliability: Comprehensive error handling");
    println!("   • Performance: Async and concurrent by design");
    println!("   • Security: Built-in protection mechanisms");
    
    Ok(())
}
